package com.nosnow.msm.utils;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

/**
 * @author by bingHeng
 * @version 1.0
 * @Create 2020/4/22 21:48
 *
 * 获取随机数
 */
public class RandomUtil {

    private static final Random random = new Random();

    private static final DecimalFormat fourdf = new DecimalFormat("0000");

    private static final DecimalFormat sixdf = new DecimalFormat("000000");

    /**
     * 生成4位随机数
     * @return
     */
    public static String getFourBitRandom() {
        return fourdf.format(random.nextInt(10000));
    }

    /**
     * 生成六位随机数
     * @return
     */
    public static String getSixBitRandom() {
        return sixdf.format(random.nextInt(1000000));
    }

    /**
     * 给定数组，抽取n个数据
     * @param list
     * @param n
     * @return
     */
    public static ArrayList getRandom(List list, int n) {
        Random random = new Random();
        HashMap<Object, Object> hashMap = new HashMap<>(16);

        // 1. 生成随机数字并存入HashMap
        for (int i = 0; i < list.size(); i++) {
            hashMap.put(random.nextInt(100) + 1, i);
        }

        // 2. 从HashMap导入数组
        Object[] robjs = hashMap.values().toArray();

        // 3. 遍历数组并打印数据
        ArrayList r = new ArrayList();
        for (int i = 0; i < n; i++) {
            r.add(list.get((int) robjs[i]));
        }
        return r;
    }
}
